<template>
  <div class="roles">
    <div class="navigation">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="box-card">
      <div class="top">
        <div class="search-content">
          <el-input placeholder="请输入用户ID" v-model="searchInput"></el-input>
          <!-- <el-input placeholder="请输入内容" v-model="input2"></el-input> -->
          <el-button
            class="search-icon"
            type="primary"
            icon="el-icon-search"
            @click="search"
          ></el-button>
        </div>
        <div class="add-role">
          <el-button type="primary" @click="addFormVisible = true"
            >添加角色</el-button
          >
        </div>
      </div>

      <template>
        <el-table :data="roleList" border style="width: 100%">
          <!-- type="expand" 可展开树形结构 -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row
                v-for="(firstItem, index) in scope.row.children"
                :key="firstItem.id"
                :class="['bdbottom', index === 0 ? 'bdtop' : '', 'vcenter']"
              >
                <el-col :span="5">
                  <div class="first">
                    <el-tag closable @close="removePower(scope.row,firstItem.id)">
                      {{ firstItem.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </div>
                </el-col>

                <el-col :span="19">
                  <el-row
                    v-for="(secondItem, index) in firstItem.children"
                    :key="secondItem.id"
                    :class="[index === 0 ? '' : 'bdtop', 'vcenter']"
                  >
                    <el-col :span="10">
                      <div class="second">
                        <el-tag
                          closable
                          type="success"
                          @close="removePower(scope.row,secondItem.id)"
                        >
                          {{ secondItem.authName }}
                        </el-tag>
                        <i class="el-icon-caret-right"></i>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="third">
                        <el-tag
                          closable
                          type="warning"
                          v-for="(thirdItem, index) in secondItem.children"
                          :key="index"
                          @close="removePower(scope.row,thirdItem.id)"
                        >
                          {{ thirdItem.authName }}
                        </el-tag>
                      </div>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column width="50" label="#" type="index"></el-table-column>
          <el-table-column
            width="220"
            prop="roleName"
            label="角色名称"
          ></el-table-column>
          <el-table-column
            width="220"
            prop="roleDesc"
            label="角色描述"
          ></el-table-column>

          <el-table-column width="350" label="操作">
            <template slot-scope="scope">
              <el-row class="btns">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteRoleDialog(scope.row.id)"
                  >删除</el-button
                >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  @click="fenpeiDialog(scope.row)"
                  >分配权限</el-button
                >
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>

    <!-- 添加角色 对话框 -->
    <el-dialog title="添加角色" :visible.sync="addFormVisible"
    @close="closeAdd"
    >
      <el-form
        :model="roleForm"
        label-width="80px"
        :rules="roleRules"
        ref="addRuleForm"
      >
        <el-form-item label="角色名称" prop="roleName" class="role-name">
          <el-input v-model="roleForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button @click="addRole" type="primary">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 角色编辑 对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editFormVisible">
      <el-form
        :model="roleForm"
        label-width="80px"
        :rules="roleRules"
        ref="editRuleForm"
      >
        <el-form-item label="角色名称" prop="roleName" class="role-name">
          <el-input
            v-model="roleForm.roleName"
            autocomplete="off"
            clearable=""
          ></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input
            v-model="roleForm.roleDesc"
            autocomplete="off"
            clearable=""
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button @click="editRole" type="primary">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 删除角色对话框 -->
    <el-dialog title="提示" :visible.sync="delRoleVisible" width="30%">
      <span>是否删除该角色？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="asRoleVisible"
     width="60%"
     @close="closeDialog"
     >
      <el-tree
        :data="treeData"
        :props="props"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="tree"
        highlight-current
        :default-checked-keys="defaultKeys"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="asRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="selectQuanxian">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 移除权限 -->
     <el-dialog title="提示" :visible.sync="removePowerVisible">
      <span>是否移除该权限</span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="removePowerVisible = false">取 消</el-button>
        <el-button @click="remove" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "roles",
  data() {
    return {
      // 角色列表
      roleList: [],

      // 是否展示添加角色的对话框
      addFormVisible: false,
      // 角色添加
      roleForm: {
        roleName: "",
        roleDesc: "",
        roleId: "",
      },
      roleRules: {
        roleName: [
          {
            required: true,
            message: "角色名称不能为空！",
            trigger: "blur",
          },
        ],
      },

      searchInput: "",
      roleInfo: {},
      // 是否展示编辑角色的对话框
      editFormVisible: false,
      // 是否展示删除角色的对话框
      delRoleVisible: false,
      roleId: "",

      // 是否展示分配权限的对话框
      asRoleVisible: false,
      props: {
          label: 'authName',
          children: 'children'
      },
      // 树形权限列表数据
      treeData:[],

      // 默认选中的节点的id值的数组 
      defaultKeys:[],

      // 是否展示移除权限对话框
      removePowerVisible:false,
      // 权限id
      rightId:'',

    };
  },
  computed: {
    // 
    // ...mapState(['roleId'])
  },
  created() {
    this.getRoleListData();
  },
  methods: {
    // 获取角色列表数据
    getRoleListData() {
      this.axios({
        method: "get",
        url: "roles",
      })
        .then((res) => {
          

          if (res.data.meta.status == 200) {
            this.roleList = res.data.data;
            
          }
        })
        .catch((err) => {
          
        });
    },
    handleNodeClick(data) {
      
    },

    // 添加角色
    addRole() {
      
      this.$refs.addRuleForm.validate((valid) => {
        //   

        if (valid) {
          this.axios({
            method: "post",
            url: "/roles",
            data: {
              roleName: this.roleForm.roleName,
              roleDesc: this.roleForm.roleDesc,
            },
          })
            .then((res) => {
              

              if (res.data.meta.status == 201) {
                this.$message.success("创建角色成功！");
                this.addFormVisible = false;
                this.getRoleListData();
              } else {
                this.$message.error("创建角色失败！");
                return;
              }
            })
            .catch((err) => {
              
            });
        } else {
          
          return false;
        }
      });
    },
    closeAdd(){
      this.$refs.addRuleForm.resetFields();
    },

    // 根据id查询角色
    search(roleInfo) {
      
      roleInfo.id = this.searchInput;
      

      this.axios({
        method: "get",
        // url:'roles/:id'
        url: `roles/${roleInfo.id}`,
      })
        .then((res) => {
          

          if (res.data.meta.status == 200) {
            this.$message.success("查询成功！");
            this.getRoleListData();
          } else {
            this.$message.error("抱歉！查无此角色！");
          }
        })
        .catch((err) => {
          
        });
      this.searchInput = "";
    },

    // 展示编辑对话框
    showEditDialog(roleInfo) {
      
      // this.editFormVisible = true;

      this.axios({
        method: "get",
        url: "roles/" + roleInfo,
      })
        .then((res) => {
          

          if (res.data.meta.status != 200) {
            this.$message.error("查询用户失败");

            // 查询失败则不打开修改对话框
            this.editFormVisible = false;
          }

          this.roleForm = res.data.data;

          this.editFormVisible = true;
        })
        .catch((err) => {
          
        });
    },

    // 编辑用户
    editRole() {
      this.$refs.editRuleForm.validate(async (valid) => {
        //   

        if (valid) {
          this.axios({
            method: "put",
            url: "roles/" + this.roleForm.roleId,
            data: {
              roleName: this.roleForm.roleName,
              roleDesc: this.roleForm.roleDesc,
            },
          })
            .then((res) => {
              

              this.$message.success("修改用户信息成功！");
              this.editFormVisible = false;
              this.getRoleListData();
            })
            .catch((err) => {
              
            });
        } else {
          
          return false;
        }
      });
    },

    // 展示删除角色的对话框
    deleteRoleDialog(id) {
      // 
      this.delRoleVisible = true;
      this.roleId = id;
      // 
    },

    //删除角色
    deleteRole() {
      // 
      this.axios({
        method: "delete",
        url: "roles/" + this.roleId,
      })
        .then((res) => {
          

          if (res.data.meta.status == 200) {
            this.$message.success("删除成功！");
            this.delRoleVisible = false;
            this.getRoleListData();
          } else {
            this.$message.error("删除失败！");
            return;
          }
        })
        .catch((err) => {
          
        });
    },

    // 展示分配权限的对话框
    fenpeiDialog(role) {
      

      this.asRoleVisible = true;

      this.roleId = role.id;
      // 

      this.axios({
        method:'get',
        // 获取树形权限列表
        url:'rights/tree'
      }).then(res=>{
        
        if(res.data.meta.status == 200){
          this.treeData = res.data.data;
          

        }
      }).catch(err=>{
        
      })

      this.getLeaKeys(role,this.defaultKeys);
      

    },

    // 通过递归的形式，获取角色下所有三级权限的id,
    // 并保存到defaultKeys数组中
    getLeaKeys(node,arr){
      
      

      // 若当前node节点不包含children属性，该节点则是第三季节点
      if(!node.children){
        return arr.push(node.id);
      }

      node.children.forEach(item=>{
        this.getLeaKeys(item,arr);
      })
    },

    // 监听关闭对话框
    // 关闭对话框时会重置defaultKeys数组
    closeDialog(){
      this.defaultKeys = [];
    },

    // 确定分配权限，关闭对话框
    selectQuanxian(){
      // 将勾选的权限id保存到数组中
      let keys = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys()
      ];

      

      // 用逗号,拼接字符串
      let strId = keys.join(',');
      

      // 

      this.axios({
        method:'post',
        url:`roles/${this.roleId}/rights`,
        data:{
          rids: strId
        }
      }).then(res=>{
        
        if(res.data.meta.status == 200){
          this.$message.success('分配权限成功！');
          this.asRoleVisible = false;
          this.getRoleListData();
        }else{
          this.$message.error('分配权限失败！');
          return;
        }
      }).catch(err=>{
        
      })
    },

    // 展示删除权限的对话框
    removePower(role,rightId) {
      
      
      
      this.roleId = role.id;
      this.rightId = rightId;

      this.removePowerVisible = true;
    },

    // 删除权限
    remove(){
      

      this.axios({
        method:'delete',
        // url:'roles/:roleId/rights/:rightId'
        url:`roles/${this.roleId}/rights/${this.rightId}`
      }).then(res=>{
        

        if(res.data.meta.status == 200){
          this.$message.success('移除权限成功！');
          this.removePowerVisible = false;
          this.getRoleListData();
        }else{
          this.$message.error('移除权限失败！');
          return;
        }
      }).catch(err=>{
        
      })
    }
  },
};
</script>

<style lang="less" scoped>
.roles {
  margin-top: 70px;
  // margin-left: 200px;
}
.box-card {
  margin-top: 22px;
  .top {
    // border: 1px solid #000;
    display: flex;
    margin-bottom: 16px;
    .search-content {
      display: flex;
    }
    .add-role {
      margin-left: 18px;
    }

    /deep/ .el-input__inner {
      // border: 1px solid #000;
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
      outline: none;
    }
    /deep/ .search-icon {
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
      background-color: #ccc;
      border-color: #ccc;
    }
  }
}
.add-user {
  margin-bottom: 16px;
}
/deep/ .el-table__cell {
  // background-color: #ccc;
  padding: 0;
  &:first-child {
    padding: 12px 0;
  }
}
.btns {
  // border: 1px solid red;
  display: flex;
  .el-button {
    // border: 1px solid #000;
    height: 30px;
    padding-left: 10px;
    padding-right: 10px;
    display: flex;
    align-items: center;
    // margin-bottom: -20px;
    /deep/span {
      // border: 1px solid #000;
      margin-top: 0px;
    }
  }
}

.el-row {
  padding-top: 10px;
  padding-bottom: 10px;
}

.first {
  // border: 1px solid #000;
  margin-left: 10px;
  display: flex;
  align-items: center;
}
.second {
  margin-left: 20px;
}
.third {
  margin-left: -40px;
  .el-tag {
    // border: 1px solid #000;
    margin-right: 12px;
    margin-bottom: 10px;
  }
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}

.role-name {
  // border: 1px solid #000;
  margin-bottom: 30px;
}
</style>